/**
 * 
 */
package com.ashun.config;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator;
import net.rubyeye.xmemcached.utils.AddrUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.util.Properties;

/**
 * MemcachedClient 构造器
 * 
 * @author chenwenshun
 * 
 */
public class TntMemcachedClientBuilder {

	private static Log log = LogFactory.getLog(TntMemcachedClientBuilder.class);

	private String servers;

	private boolean failover = true;

	public TntMemcachedClient build() {

		TntMemcachedClient tntClient = null;
		// String servers =
		// DictUtil.getDictNameByCd(DictContants.MEMCACHED_PROPERTIES,
		// DictContants.memcachedPropties.servers);
		// String servers = "192.168.0.230:11211,192.168.0.230:11213";
		if ( StringUtils.isNotBlank(servers) ) {
			try {
				MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddressMap(servers));
				// builder.setConnectionPoolSize(5);
				builder.setFailureMode(failover);// 启用主备,必须设置该属性
				// repcached-2.3.1-1.4.13.patch.gz不支持该模式同步
				// builder.setCommandFactory(new BinaryCommandFactory());
				builder.setSessionLocator(new KetamaMemcachedSessionLocator());//一致性hash
				MemcachedClient mc = builder.build();
				tntClient = new TntMemcachedClient(mc);
			} catch (Exception e) {
				log.error("init MemcachedClient error", e);
			}
		} else {
			log.warn("please set memcache servers!");
		}
		return tntClient;
	}

	public void setServers(String servers) {

		this.servers = servers;
	}

	public void setFailover(boolean failover) {

		this.failover = failover;
	}
}
